#!/usr/bin/env python

from __future__ import with_statement
from ctypes import *

import os
import cgi
import socket
import win32con
import urlparse
import mimetypes
import encoder.pipe
import SocketServer
import BaseHTTPServer
import controller

BUFSIZE = 4096

__all__ = ("RequestHandler")
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    i = 0

    def do_dispatch(self, body):
        self.url = self.path
        pieces = urlparse.urlparse(self.path)
        self.path = pieces[2]
        self.query = cgi.parse_qs(pieces[4])

        url = {
            "/": self.serve_main,
            "/stop.do": self.serve_shutdown,
            "/media.get": self.serve_stream,
            "/list.get": self.serve_list,
            #"/listXML.get": self.serve_listXML,
            }

        try:
            url[self.path](body)
        except KeyError:
            self.send_error(404, "File not found 0")
    # do_dispatch()


    def do_GET(self):
        self.do_dispatch(True)
    # do_GET()
    def do_HEAD(self):
        self.do_dispatch(False)
    # do_HEAD()

    def serve_main(self, body):
        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.send_header('Connection', 'close')
        self.end_headers()
        if body:
            print "Hello, client!"
            #do nothing
            pass
    # serve_main()

    def serve_shutdown(self, body):
        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.send_header('Connection', 'close')
        self.end_headers()
        if body:
            pass
        #mencoder stop
        self.server.server_close()
    # serve_shutdown()

    def serve_list(self, body):
        if(self.query.has_key("type")):
            listType = self.query.get("type", None)[0]
            if( (listType == "") or (listType == "xml")):
                self.generate_listXML(body)
            elif(listType == "html"):
                self.generate_listHTML(body)
        else:
            self.generate_listXML(body)

    # serve_list()

    def generate_listHTML(self, body):
        self.send_response(200)
        #self.send_header("Content-Type", "application/octet-stream")
        self.send_header("Content-Type", "text/html")
        self.send_header('Connection', 'close')
        self.end_headers()

        if body:
            if (not os.path.exists("echoes.html")):
                with open("echoes.html", "w") as listFile:
                    with open("head.snr", "r") as header:
                        for line in header:
                            listFile.write(line)
                    listFile.write("</body>\n</html>")
                    listFile.close()

            list = file("echoes.html")
            bf = list.read(BUFSIZE)
            while (bf):
                    self.wfile.write(bf)
                    bf = list.read(BUFSIZE)
            list.close()

    def generate_listXML(self, body):
        self.send_response(200)
        #self.send_header("Content-Type", "application/octet-stream")
        self.send_header("Content-Type", "text/html")
        self.send_header('Connection', 'close')
        self.end_headers()

        if body:
            if (not os.path.exists("echoes.list")):
                with open("echoes.list", "w") as listFile:
                    listFile.write("<ECHOES>\n</ECHOES>")
                    listFile.close()

            list = file("echoes.list")
            bf = list.read(BUFSIZE)
            while (bf):
                    self.wfile.write(bf)
                    bf = list.read(BUFSIZE)
            list.close()
    # serve_list()


    def serve_stream(self, body):

        #início do protocolo
        id = self.query.get("id", None)[0]
        if not id:
            self.send_error(400, "Bad request!")
            return

        type = getType(id)

        if type == "video":

            res_default = "resdefault"
            codec_default = "codecdefault"
            stream_default = "streamdefault"

            if self.query.has_key("res"):
                res = self.query.get("res", None)[0]
            else: res = res_default

            if self.query.has_key("codec"):
                codec = self.query.get("codec", None)[0]
            else: codec = codec_default

            if self.query.has_key("stream"):
                stream = self.query.get("stream", None)[0]
            else: stream = stream_defaul

        elif type == "audio":
            pass
        elif type == "image":
            pass
        else: print "Fail!"

        print "id:" + id + " res:" + res + " codec:" + codec + " stream:" + stream
        print "Legal!"
        #fim do protocolo

        filename = controller.getPath(id)
        try: existe = os.path.exists(filename)
        except:
            self.send_error(404, "File not found, 2")
            return

        if not existe:
            self.send_error(404, "File not found 3")
            return


        media = controller.getMedia(id) #aqui ta pegando a midia


        hPipe = encoder.pipe.generatePipe(filename, tvResolution, media, streamType)

        print "Encoded Everything" #debug
        print mimetypes.guess_type(filename)[0]
        data = create_string_buffer(BUFSIZE)
        cbRead = c_ulong(0)
        self.send_response(200)
        if media == 2:
            if streamType == "v":
                self.send_header("Content-Type", "application/octet-stream")
            if streamType == "a":
                self.send_header("Content-Type", "image/jpeg")
        else:
            self.send_header("Content-Type", mimetypes.guess_type(filename)[0])
        self.send_header("Cache-Control","no-cache")
        self.end_headers()
        print "aqui"
        while(1):
            fSuccess = windll.kernel32.ReadFile(hPipe,
                                                data,
                                                BUFSIZE,
                                                byref(cbRead),
                                                None)
            if(cbRead.value == 0L):
                break
            self.wfile.write(data.raw[0:cbRead.value])
            #print enviado

        windll.kernel32.FlushFileBuffers(hPipe)
        windll.kernel32.DisconnectNamedPipe(hPipe)
        windll.kernel32.CloseHandle(hPipe)
        print "Stream sent"
    # serve_stream()

# RequestHandler